import * as React from 'react';
import {
    Button,
    Image,
    SafeAreaView,
    ScrollView,
    StyleSheet,
    Text,
    FlatList,
    TouchableOpacity,
    View,
} from 'react-native';
import {DataTable, Dialog, Paragraph, Portal, Provider} from 'react-native-paper';
import {
    DOMAIN_URL,
    deptInfoGet,
    noticeUnread,
    newsList,
    eventList,
    studyList,
    newsRecent,
    getCurrentUserInfo,
    getTotalPointsPs,
    getMouthPointsPs,
    getTotalPointsRankPs,
    getMouthPointsRankPs,
    getGroupPointsRankPs,
} from '../util/api';
import AsyncStorage from '@react-native--storage/-storage';
import {useState} from 'react';
import {style} from '../theme';
import {PAGENAME} from '../util/PageName';

class ScoreScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // const [selectedId, setSelectedId] = useState(null);
            // const [userScoreItemList, setUserScoreItemList] = useState([]);
            // const [scoreInfo, setScreInfo] = React.useState({
            //     total: '*',
            //     totalRank: '*',
            //     month: '*',
            //     monthRank: '*',
            // });
            selectedId: null,
            userScoreItemList: null,
            scoreInfo: {
                total: '*',
                totalRank: '*',
                month: '*',
                monthRank: '*',
            },
        };
        this.initPage();

    }

    componentDidMount() {
        this.subscription = this.props.navigation.addListener('focus', () => {
            // do something
            console.log('event detail');
            this.initPage();
        });
    }

    componentWillUnmount() {
        this.subscription();
    }

    // 排序函数
    getRank = (value, Items) => {
        for (let i = 0; i < Items.length; i++) {
            if (Items[i].userInfo.loginName === value) {
                return Items[i].pointRank;
            }
        }
        return 0;
    };

    //初始化
    initPage = () => {
        // 初始化
        getTotalPointsPs(global.USER.username).then(res => {
            console.log(res);
            const {scoreInfo} = this.state
            scoreInfo.total = res.data;
            this.setState({
                scoreInfo: scoreInfo
            })
        })
        getMouthPointsPs(global.USER.username).then(res => {
            console.log(res);
            const {scoreInfo} = this.state
            scoreInfo.month = res.data;
            this.setState({
                scoreInfo: scoreInfo
            })
        })
        getTotalPointsRankPs(null).then(res => {
            console.log(res);
            const {scoreInfo} = this.state
            scoreInfo.totalRank = this.getRank(global.USER.username, res.data);
            this.setState({
                scoreInfo: scoreInfo
            })
        })
        getMouthPointsRankPs(null).then(res => {
            console.log(res);
            const {scoreInfo} = this.state
            scoreInfo.monthRank = this.getRank(global.USER.username, res.data);
            this.setState({
                scoreInfo: scoreInfo
            })
        })
        this.mouthPage();

    };
    //月度积分排名
    mouthPage = () => {
        getMouthPointsRankPs(null).then(res => {
            console.log(res);
            this.setState({
                userScoreItemList: res.data
            })
        })

    };
    //总积分排名
    totalPage = () => {
        getTotalPointsRankPs(null).then(res => {
            console.log(res);
            this.setState({
                userScoreItemList: res.data
            })
        })

    };
    //小组积分排名
    groupPage = () => {
        getGroupPointsRankPs(null).then(res => {
            console.log(res);
            this.setState({
                userScoreItemList: res.data
            })
        })

    };

    renderItem = ({item}) => {
        return (
            <View style={styles.indexDataRow} key={'event:' + item}>
                <TouchableOpacity
                    onPress={() => {
                        this.setState({
                            selectedId: item?.userInfo?.userId
                        })
                    }}
                    style={{flexDirection: 'row', alignItems: 'center'}}>
                    {/* <View style={{ marginLeft: 4, justifyContent: 'space-between' }}>
                        <Text>{item.pointRank}</Text>
                    </View> */}
                    <View style={{flexDirection: 'row', alignItems: 'center', width: global.SCREEN.width - 100}}>
                        <View style={{flexDirection: 'row', marginLeft: 4, justifyContent: 'space-between'}}>
                            <Image
                                style={{width: 50, height: 50, borderRadius: 50}}
                                source={{
                                    uri: `${DOMAIN_URL}/file/images/touxiang.jpg`,
                                }}></Image>
                        </View>
                        <View style={{marginLeft: 8, justifyContent: 'space-between'}}>
                            <Text style={{fontWeight: 'bold', fontSize: 12}}
                                  numberOfLines={1}
                                  ellipsizeMode={'tail'}>
                                {item?.userInfo?.userName}
                            </Text>
                            <Text style={{
                                color: 'rgb(245, 86, 81)',
                                marginTop: 4,
                                fontSize: 12
                            }}>{item?.userInfo?.group?.groupName}</Text>
                        </View>
                    </View>

                    <View style={{marginLeft: 4, width: 100, flexDirection: 'row', alignItems: 'baseline'}}>
                        <Text style={{fontSize: 32, textAlign: 'right'}}>{item?.score}</Text>
                        <Text>分</Text>
                    </View>

                </TouchableOpacity>
            </View>
        );
    }
    listHeader = ({item}) => {
        const {scoreInfo} = this.state
        return (
            <View
                style={{
                    // flexDirection: 'row',
                    // justifyContent: 'space-between',
                    // alignItems: 'center',
                }}>
                <View
                    style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-around',
                        backgroundColor: 'rgb(245, 86, 81)',
                        margin: 24,
                        borderRadius: 16,
                        borderWidth: 4,
                        borderColor: '#ddd',
                    }}>
                    {/*总积分*/}

                    <View style={styles.scoreTotal}>
                        <Text style={styles.label}>总积分: {scoreInfo.total}</Text>
                        <Text style={styles.label}>排名: {scoreInfo.totalRank}</Text>
                    </View>
                    {/*月积分*/}
                    <View style={styles.scoreTotal}>
                        <Text style={styles.label}>月积分: {scoreInfo.month}</Text>
                        <Text style={styles.label}>排名: {scoreInfo.monthRank}</Text>
                    </View>

                </View>
                <View>
                    <View style={{
                        flexDirection: 'row',
                        marginVertical: 8,
                        alignSelf: 'center',
                        width: 260,
                        justifyContent: 'space-around',
                    }}>
                        <TouchableOpacity style={styles.button} onPress={() => {
                            console.log('Pressed');
                            this.mouthPage();
                        }}>
                            <Text style={styles.buttonText}>{'月'}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.button} onPress={() => {
                            console.log('Pressed');
                            this.totalPage();
                        }}>
                            <Text style={styles.buttonText}>{'总'}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.button} onPress={() => {
                            console.log('Pressed');
                            this.groupPage();
                        }}>
                            <Text style={styles.buttonText}>{'组'}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>

        );
    };


    render() {
        const {navigation} = this.props;
        const {scoreInfo} = this.state
        return (
            <SafeAreaView>
                <FlatList
                    data={this.state.userScoreItemList}
                    renderItem={this.renderItem}
                    ListHeaderComponent={this.listHeader}
                    keyExtractor={item => item?.userInfo?.userId}
                    extraData={this.state.selectedId}
                />
            </SafeAreaView>
        );
        // </ImageBackground>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // paddingTop: StatusBar.currentHeight,
    },
    scoreTotal: {
        marginTop: 8,
        paddingVertical: 40,
        // marginLeft: 35
    },
    label: {
        fontSize: 18,
        color: '#fff',
        fontWeight: 'bold',
        padding: 6,
    },
    value: {
        marginLeft: 16,
        fontSize: 16,
        fontWeight: '600'
    },
    userRow: {
        flexDirection: 'row',
        margin: 4
    },
    indexDataRow: {
        margin: 4,
        marginBottom: 8,
        marginTop: 8,
        marginLeft: 8,
    },
    button: {
        backgroundColor: 'rgb(245, 86, 81)',
        borderColor: '#ddd',
        padding: 12,
        borderWidth: 2,
        borderRadius: 5,
        alignItems: 'center',
    },
    buttonText: {
        color: '#FFFFFF',
        fontSize: 16,
        fontWeight: 'bold',
    },
});

export default ScoreScreen;
